const { poolQuery } = require("../utils/db");

// 封装分页数据
function getPageData(page, limit, tableName, condition, callback) {
  const offset = (page - 1) * limit;
  const listSql = `${tableName} ${
    condition ? "WHERE " + condition : ""
  } order by id desc LIMIT ?,?`;
  const sql = `SELECT * FROM ${listSql}`;
  const params = [offset, limit];
  // 查询分页数据
  poolQuery(sql, params, (error, results) => {
    if (error) {
      console.error("分页查询失败:", error);
      return callback(error, null, null);
    }

    // 查询总行数
    const countSql = `SELECT COUNT(*) AS count FROM ${listSql}`;
    poolQuery(countSql, params, (err, countResults) => {
      if (err) {
        console.error("查询总行数失败:", err);
        return callback(err, null, null);
      }
      const totalCount = countResults.length ? countResults[0].count : 0;
      // const totalPages = Math.ceil(totalCount / limit);
      callback(null, results, totalCount);
    });
  });
}
module.exports = { getPageData };
